<template>
  <view class="my-settle-container">
    <!-- 全选框 -->
    <label class="radio">
      <radio color="#C00000" :checked="isFullCheck" @click="toggleCheck"><text>全选</text></radio>
    </label>
    
    <!-- 合计 -->
    <view class="amount-box">
      合计：<text class="amount">$ {{chekedGoodsAmount | toFixed}}</text>
    </view>
    
    <!-- 结算按钮 -->
    <view class="btn-settle" @click="settlement">结算({{checkCount}})</view>
  </view>
</template>

<script>
  import { mapState, mapGetters, mapMutations } from 'vuex'
  export default {
    name:"my-settle",
    data() {
      return {
        second: 3,
        timer: null
      };
    },
    filters: {
      toFixed(num) {
        return num.toFixed(2)
      }
    },
    computed: {
      ...mapGetters('m_cart',['checkCount', 'total', 'chekedGoodsAmount']),
      ...mapGetters('m_user',['addStr']),
      ...mapState('m_user', ['token']),
      ...mapState('m_cart', ['cart']),
      isFullCheck() {
          return  this.checkCount === this.total
      }
    },
    methods: {
      ...mapMutations('m_cart',['updateCheckState']),
      ...mapMutations('m_user',['updateRedirectInfo']),
      toggleCheck() {
        this.updateCheckState(!this.isFullCheck)
      },
      settlement() {
        // 判断是否勾选了要结算的商品
        if (!this.checkCount) return uni.$showMsg('请选择要结算的商品')
        
        // 判断用户是否填写了收货地址
        if (!this.addStr) return uni.$showMsg('请设置收货地址')
        
        // 判断用户是否已经登录
        // if (!this.token) return uni.$showMsg('请先登录')
        if (!this.token) return this.delayNavigate()
        
        this.payOrder()
      },
      async payOrder() {
        // 创建订单
        const orderInfo = {
          order_price: 0.01,
          consignee_addr: this.addStr,
          goods: this.cart.filter(x => x.goods_state).map(x => ({ 
            goods_id: x.goods_id, 
            goods_number: x.goods_count,
            goods_price: x.goods_price
          }))
        }
        // 发起请求创建订单
        const {data: res} = await uni.$http.post('/api/public/v1/my/orders/create', orderInfo)
        if (res.meta.status != 200) return uni.$showMsg()
        
        // 得到服务器响应的订单编号
        const orderNumber = res.message.order_number
        
        // 订单预支付
        const {data: res2} = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', {
          order_number: orderNumber
          })
        if (res2.meta.status != 200) return uni.$showMsg('预订单生成失败')
        
        // 得到订单支付相关的必要参数
        const payInfo = res2.message.pay
        // console.log(payInfo)
        
        // 发起微信支付
        const [err, succ] = await uni.requestPayment(payInfo)
        console.log(err)
        // 未完成支付
        if (err) return uni.$showMsg('订单未支付!!')
        // 完成支付
        const {data: res3} = await uni.$http.post('/api/public/v1/my/orders/chkOrder', {
          order_number: orderNumber
          })
        if (res3.meta.status != 200) return uni.$showMsg('订单未支付')
        
        // 检测订单支付完成
        uni.showToast({
          title: '支付完成',
          icon: 'success'
        })
      },
      showTips(n) {
        // 调用 uni.showToast() 方法，展示提示消息
        uni.showToast({
          // 不展示任何图标
          icon: 'none',
          // 提示的消息
          title: '请登录后再进行结算，' + n + '秒后将自动跳转到登录页面',
          // 为页面添加透明遮罩，防止点击穿透
          mask: true,
          // 1.5 秒后自动消失
          duration: 1500
        })
      },
      delayNavigate() {
        // 展示提示消息
        this.showTips(this.second)
        
        // 创建定时器
        this.timer = setInterval(()=>{
          this.second--
          if (this.second <= 0) {
            clearInterval(this.timer)
            this.second = 3
            // 跳转到登录页
            uni.switchTab({
              url: '../../pages/my/my',
              // 页面跳转成功之后的回调函数
              success: () => {
                this.updateRedirectInfo({
                  // 跳转方式
                  openType: 'switchTab',
                  // 从哪个页面跳转过去的
                  url: '../../pages/cart/cart'
                })
              }
            })
            return 
          }
        
          this.showTips(this.second)
        }, 1000)
      }
    }
  }
</script>

<style lang="scss">
.my-settle-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  z-index: 1;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  padding-left: 5px;
  
  .radio {
    display: flex;
    align-items: center;
  }
  
  .amount-box {
    .amount {
      color: #C00000;
      font-weight: bold;
    }
  }
  
  .btn-settle {
    background-color: #C00000;
    height: 50px;
    color: white;
    text-align: center;
    line-height: 50px;
    padding: 0 10px;
    min-width: 100px;
  }
}
</style>
